//
//  YPInvestViewController.m
//  ChengHuiTong
//
//  Created by KiVen on 15/11/2.
//  Copyright © 2015年 张文权. All rights reserved.
//

#import "YPInvestViewController.h"
#import "YPInvestCell.h"
#import "YPInvestDetailViewController.h"
#import "YPInvestModel.h"
#import "XButton.h"
#import "YPInvestParameter.h"
#import "YPRecommendCell.h"
#import "YPZQDetailViewController.h"

@interface YPInvestViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{

    NSMutableArray * _investArray;
    NSMutableArray * _zqArray;
    
    NSMutableDictionary *_zqParameterDic;
    int _investPage;
    int _zqPage;
    BOOL _hasShowWarn;

}
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)UITableView *investTableView;
@property(nonatomic, strong)UITableView *zqTableView;
@property(nonatomic, weak)XButton *currentSelectButton;
@property(nonatomic, weak)XButton *zqCurrentSelectButton;
@property(nonatomic, strong)YPInvestParameter * parameter;
@property(nonatomic, strong)UISegmentedControl *segement;


@end

@implementation YPInvestViewController

#pragma mark -- lazzy
- (UISegmentedControl *)segement{
    
    if (!_segement) {
        _segement = [[UISegmentedControl alloc]initWithItems:@[@"投资理财",@"债权转让"]];
        _segement.bounds = CGRectMake(0, 0, 200, 28);
        _segement.tintColor = [UIColor whiteColor];
        [_segement addTarget:self action:@selector(segmentAction) forControlEvents:UIControlEventValueChanged];
        _segement.selectedSegmentIndex = 0;
    }
    return _segement;
}

- (UIScrollView *)scrollView{
    
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, _scrollView.height);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.scrollEnabled = NO;
    }
    return _scrollView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setUpData];
    
    [self setUpUI];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"小诚优选"];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [MobClick endLogPageView:@"小诚优选"];
}

#pragma mark - 私有方法
- (void)setUpData{
    
    _investArray = [[NSMutableArray alloc]initWithCapacity:0];
    _zqArray = [NSMutableArray array];
    _parameter = [[YPInvestParameter alloc]init];
    _parameter.type = 1;
    _parameter.order = 1;
    _investPage = _zqPage = 1;
    
    _zqParameterDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(0),@"type",@(2),@"order",@(_zqPage),@"page",nil];
}

- (void)setUpUI{
    
    self.navigationItem.titleView = self.segement;
    [self.view addSubview:self.scrollView];
    [self creatInvestView];
    [self creatZqView];
    
}

- (void)creatInvestView{
    
    UIView *headView = [self getFilterViewWithTitleArray:@[ @"项目进度", @"项目期限",@"年化收益"]
                                                isInvest:YES];
    self.investTableView = [self getTableViewWithInvest:YES];
    [self.scrollView addSubview:headView];
    [self.scrollView addSubview:self.investTableView];
    [self.investTableView.header beginRefreshing];
    
}

- (void)creatZqView{
    
    UIView *headView = [self getFilterViewWithTitleArray:@[ @"项目规模", @"原标收益",@"还款日期"]
                                                isInvest:NO];
    self.zqTableView = [self getTableViewWithInvest:NO];
    [self.scrollView addSubview:headView];
    [self.scrollView addSubview:self.zqTableView];
}

- (UIView *)getFilterViewWithTitleArray:(NSArray *)titleArray
                               isInvest:(BOOL)isInvest{
    
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(isInvest?0:SCREEN_WIDTH, 0, SCREEN_WIDTH, 40)];
    headerView.backgroundColor = [UIColor whiteColor];
    
    CGFloat width = SCREEN_WIDTH/titleArray.count;
    for (int i = 0 ; i < titleArray.count ; i++) {
        
        XButton * filterButton = [XButton buttonWithType:UIButtonTypeCustom];
        filterButton.tag = isInvest ? i+1000 : i+101;
        filterButton.frame = CGRectMake(i*width,0, width, 40);
        [filterButton setTitle:titleArray[i] forState:UIControlStateNormal];
        filterButton.titleLabel.font = [UIFont systemFontOfSize:13];
        filterButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [filterButton addTarget:self action:@selector(filterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            if (isInvest) {
                self.currentSelectButton = filterButton;
                filterButton.isChoice= YES;
            }else{
                filterButton.isChoice= NO;
            }
        }else{
            filterButton.isChoice = NO;
        }
        [filterButton setTitleLeftImageRightWithWidthMiddleSpace:5];
        [headerView addSubview:filterButton];
        
        UILabel * lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 39.5, SCREEN_WIDTH, .5)];
        lineLabel.backgroundColor = kColor_cellBorderColor;
        [headerView addSubview:lineLabel];
        
    }
    [headerView addLineWithFrame:CGRectMake(width, 10, 0.5, 20) color:kColor_cellBorderColor];
    [headerView addLineWithFrame:CGRectMake(width*2, 10, 0.5, 20) color:kColor_cellBorderColor];
    
    return headerView;
}

- (UITableView *)getTableViewWithInvest:(BOOL)isInvest{
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(isInvest?0:SCREEN_WIDTH, 40, SCREEN_WIDTH, self.scrollView.height - 40) style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.scrollsToTop = YES;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [tableView addGifHeaderWithRefreshingBlock:^{
        if (isInvest) {
            [self requestHeader];
        }else{
            _zqPage = 1;
            self.zqCurrentSelectButton.isChoice = NO;
            [NSMutableDictionary dictionaryWithObjectsAndKeys:@(0),@"type",@(2),@"order",@(_zqPage),@"page",nil];
            [_zqParameterDic setValuesForKeysWithDictionary:@{@"type":@(0),@"order":@(0)}];
            [self requestZqData];
        }
        
    }];
    
    tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (isInvest) {
            _investPage++;
            [self requestFooter];
        }else{
            _zqPage++;
            [self requestZqData];
        }
    }];
    
    return tableView;
    
}

#pragma mark -- 请求数据
- (void)requestHeader {
    
   YPInvestmentBin * bin = [[YPInvestmentBin alloc]init];
    bin.option = 1;
    bin.type = _parameter.type;
    bin.order =  _parameter.order;
    bin.page = _investPage = 1;
    
    NSLog(@"%d",bin.option);
    NSLog(@"%d",bin.type);
    NSLog(@"%d",bin.order);
    NSLog(@"%d",bin.page);
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_INVESTMENT withData:[bin dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        NSLog(@"responseDictionary-----%@",responseDictionary);

        [_investArray removeAllObjects];
        if ([responseDictionary[@"status"] intValue]== 0) {

            NSMutableArray * dataArray = responseDictionary[@"list"];
            
            [dataArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                YPInvestModel * model = [[YPInvestModel alloc]initWithDictionary:obj];
                [_investArray addObject:model];
            }];
            
            [_investTableView reloadData];
            [_investTableView.header endRefreshing];
            [_investTableView.footer endRefreshing];

            if ( dataArray.count <5) {
                [_investTableView reloadData];
                [_investTableView.header endRefreshing];
                [_investTableView.footer endRefreshing];
                [_investTableView.footer noticeNoMoreData];
                
            }

        }

    } withFailedBlock:^(NSError *error) {
        [_investTableView.header endRefreshing];
        [_investTableView.footer endRefreshing];

    }withIndicator:NO  atView:self.view];

}

- (void)requestFooter{
    
    YPInvestmentBin * bin = [[YPInvestmentBin alloc]init];
    bin.option = 1;
    bin.type = _parameter.type;
    bin.order =  _parameter.order;
    bin.page = _investPage;


    [YPHttpRequestMethod sendAsyRequestURL:CMD_INVESTMENT withData:[bin dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
   
        NSLog(@"responseDictionary==%@",responseDictionary);
        
        if ([responseDictionary[@"status"] intValue]== 0) {
            
            NSMutableArray * dataArray = responseDictionary[@"list"];
            
            [dataArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                YPInvestModel * model = [[YPInvestModel alloc]initWithDictionary:obj];
                [_investArray addObject:model];
            }];
            
            [_investTableView reloadData];
            [_investTableView.header endRefreshing];
            [_investTableView.footer endRefreshing];
            
            if ( dataArray.count <5) {
                [_investTableView reloadData];
                [_investTableView.header endRefreshing];
                [_investTableView.footer endRefreshing];
                [_investTableView.footer noticeNoMoreData];
                
            }
            
        }
        
        
    } withFailedBlock:^(NSError *error) {
        [_investTableView.header endRefreshing];
        [_investTableView.footer endRefreshing];
        
        
    }withIndicator:NO  atView:self.view];

    
}

- (void)requestZqData{
    
    [_zqParameterDic setObject:@(_zqPage) forKey:@"page"];
    
    NSLog(@"_zqParameterDic:%@",_zqParameterDic);
    [YPHttpRequestMethod sendAsyRequestURL:CMD_ZQZRLIST withData:_zqParameterDic withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [_zqTableView.header endRefreshing];
        [_zqTableView.footer endRefreshing];
        
        
//        if ([REALSTRING(responseDictionary[@"tips"]) length] > 0 && !_hasShowWarn) {
//            [self showWarnViewWithText:responseDictionary[@"tips"] block:nil];
//            _hasShowWarn = YES;
//        }
        
        if ([responseDictionary[@"status"] intValue]== 0) {
            
            if (_zqPage == 1) {
                [_zqArray removeAllObjects];
            }
            NSMutableArray * dataArray = responseDictionary[@"list"];
            [dataArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                ZQListModel * model = [[ZQListModel alloc]initWithDic:obj];
                [_zqArray addObject:model];
            }];
            
            if ( dataArray.count <5)
            {
                [_zqTableView.footer noticeNoMoreData];
            }
            [_zqTableView reloadData];
            
        }
        
    } withFailedBlock:^(NSError *error) {
        [_investTableView.header endRefreshing];
        [_investTableView.footer endRefreshing];
        
    }withIndicator:NO  atView:self.view];

}

#pragma mark - 系统委托方法(UITableViewDelegate)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.segement.selectedSegmentIndex == 0? _investArray.count:_zqArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 110;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.segement.selectedSegmentIndex == 0) {
        YPInvestModel * model = [_investArray objectAtIndex:indexPath.row];
        
        YPInvestCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[YPInvestCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.model = model;
        return cell;
    }else{
        
        YPRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendCell"];
        if (!cell) {
            cell = [[YPRecommendCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RecommendCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.zqModel = _zqArray[indexPath.row];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.segement.selectedSegmentIndex == 0) {
        YPInvestDetailViewController * investDetailVC = [[YPInvestDetailViewController alloc]init];
        YPInvestModel * model = [_investArray objectAtIndex:indexPath.row];
        investDetailVC.investModel = model;
        investDetailVC.reloadProgress=^(NSString*number){
            
            YPInvestCell*cell=(YPInvestCell*)[tableView cellForRowAtIndexPath:indexPath];
            
            model.progress_bar=number;
            
            [cell setModel:model];
            
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
        };
        
        [self.navigationController pushViewController:investDetailVC animated:YES];
    }else{
        
        YPZQDetailViewController *zqDetailVC = [[YPZQDetailViewController alloc]init];
        ZQListModel *model = _zqArray[indexPath.row];
        zqDetailVC.complete = model.status.integerValue == 0?NO:YES;
        zqDetailVC.tid = model.tid;
        [self.navigationController pushViewController:zqDetailVC animated:YES];
    }
    
    
}

#pragma mark - 事件响应
- (void)segmentAction{
    
    self.scrollView.contentOffset = CGPointMake(self.segement.selectedSegmentIndex*SCREEN_WIDTH, 0);
    if (_zqArray.count == 0) {
        [self.zqTableView.header beginRefreshing];
    }
}

- (void)filterButtonClick:(XButton *)sender{
    
    if (self.segement.selectedSegmentIndex == 0) {
        
        [_investTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        
        if (sender == self.currentSelectButton) {
            if (sender.customState == 0) { //升序
                sender.customState = 1;
                _parameter.order =1;
            }
            else{ //降序
                sender.customState = 0;
                _parameter.order =2;
            }
        }else{
            _parameter.order = 1;
            self.currentSelectButton.isChoice = NO;
            sender.isChoice = YES;
            self.currentSelectButton = sender;
            
        }
        _parameter.type = (int)sender.tag == 1000?1:(sender.tag == 1001?4:3);
        [self requestHeader];
        
    }else{
        
        [_zqTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        
        if (sender == self.zqCurrentSelectButton) {
            if (sender.customState == 0) { //升序
                sender.customState = 1;
                [_zqParameterDic setObject:@1 forKey:@"order"];
            }
            else{ //降序
                sender.customState = 0;
                [_zqParameterDic setObject:@2 forKey:@"order"];
            }
        }else{
            [_zqParameterDic setObject:@1 forKey:@"order"];
            self.zqCurrentSelectButton.isChoice = NO;
            sender.isChoice = YES;
            
        }
        self.zqCurrentSelectButton = sender;
        [_zqParameterDic setObject:@(sender.tag - 100) forKey:@"type"];
        _zqPage = 1;
        [self requestZqData];
    }
}

@end
